<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录 - 校园助手</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#EC4899', // 主色调：粉色
                        secondary: '#F472B6', // 辅助色：浅粉色
                        accent: '#BE185D', // 强调色：深粉色
                        dark: '#1E293B', // 深色
                        light: '#FDF2F8'  // 浅色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-primary {
                background: linear-gradient(135deg, #EC4899 0%, #F472B6 100%);
            }
            .gradient-secondary {
                background: linear-gradient(135deg, #F472B6 0%, #FB7185 100%);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .glow {
                box-shadow: 0 0 15px rgba(236, 72, 153, 0.3);
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md bg-white rounded-xl shadow-lg overflow-hidden">
        <!-- 登录头部 -->
        <div class="bg-gradient-primary p-6 text-white text-center">
            <div class="flex justify-center mb-4">
                <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center">
                    <i class="fa fa-code text-3xl"></i>
                </div>
            </div>
            <h1 class="text-2xl font-bold">校园助手</h1>
            <p class="mt-2 text-white/80">请登录您的账号</p>
        </div>
        
        <!-- 登录表单 -->
        <div class="p-6">
            <form id="login-form" class="space-y-4">
                <div>
                    <label for="login-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <div class="relative">
                          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                              <i class="fa fa-user text-primary/70"></i>
                          </div>
                          <input type="text" id="login-username" class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入用户名" required>
                      </div>
                </div>
                <div>
                    <label for="login-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <div class="relative">
                          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                              <i class="fa fa-lock text-primary/70"></i>
                          </div>
                          <input type="password" id="login-password" class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入密码" required>
                      </div>
                </div>
                <div>
                    <label for="login-captcha" class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
                    <div class="flex space-x-2">
                        <div class="relative flex-1">
                              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                  <i class="fa fa-shield text-primary/70"></i>
                              </div>
                              <input type="text" id="login-captcha" class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入验证码" required>
                          </div>
                        <div class="relative">
                            <img id="login-captcha-image" src="" alt="验证码" class="h-12 w-36 rounded-lg cursor-pointer object-cover border border-gray-300" title="点击刷新验证码">
                            <input type="hidden" id="login-captcha-token">
                        </div>
                    </div>
                </div>
                <div class="flex justify-between items-center">
                    <div class="flex items-center">
                        <input type="checkbox" id="remember-me" class="h-4 w-4 text-primary border-primary/30 rounded focus:ring-primary">
                        <label for="remember-me" class="ml-2 block text-sm text-gray-700">记住我</label>
                    </div>
                    <button type="button" id="forgot-password-button" class="text-sm text-primary hover:text-primary/80 transition-custom">忘记密码？</button>
                </div>
                <button type="submit" id="login-submit-button" class="w-full px-4 py-3 gradient-secondary text-white font-medium rounded-lg hover:opacity-90 transition-custom flex items-center justify-center shadow-md">
                    <i class="fa fa-sign-in mr-2"></i>登录
                </button>
                
                <!-- 预设账号信息 -->
                <div class="mt-4 p-3 bg-blue-50 rounded-lg border border-blue-100">
                    <div class="text-sm text-blue-800 font-medium mb-2">
                        <i class="fa fa-info-circle mr-1 text-blue-600"></i>预设账号信息
                    </div>
                    <div class="grid grid-cols-2 gap-2 text-xs">
                        <div class="p-2 bg-white rounded border border-gray-200">
                            <div class="text-gray-500">管理员账号</div>
                            <div class="font-medium">用户名: admin</div>
                            <div class="font-medium">密码: admin123</div>
                        </div>
                        <div class="p-2 bg-white rounded border border-gray-200">
                            <div class="text-gray-500">普通用户账号</div>
                            <div class="font-medium">用户名: user</div>
                            <div class="font-medium">密码: user123</div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center text-sm text-gray-600">
                还没有账号？<button type="button" id="switch-to-register" class="text-primary hover:text-primary/80 transition-custom font-medium">立即注册</button>
            </div>
            
            <!-- API测试按钮 -->
            <div class="text-center mt-4">
                <button type="button" id="test-api-button" class="text-xs text-gray-500 hover:text-primary transition-custom">
                    <i class="fa fa-wrench mr-1"></i>测试API连通性
                </button>
            </div>
            </form>
        </div>
    </div>
    
    <!-- 注册模态框 -->
    <div id="register-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold text-gray-800">用户注册</h3>
                <button id="close-register-modal" class="text-gray-400 hover:text-gray-600 transition-custom">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <form id="register-form" class="space-y-4">
                <div>
                    <label for="register-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="register-username" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入用户名" required>
                </div>
                <div>
                    <label for="register-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="register-password" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入密码" required>
                </div>
                <div>
                    <label for="register-captcha" class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
                    <div class="flex space-x-2">
                        <input type="text" id="register-captcha" class="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-custom" placeholder="请输入验证码" required>
                        <div class="relative">
                            <img id="register-captcha-image" src="" alt="验证码" class="h-12 w-36 rounded-lg cursor-pointer object-cover border border-gray-300" title="点击刷新验证码">
                            <input type="hidden" id="register-captcha-token">
                        </div>
                    </div>
                </div>
                <button type="submit" id="register-submit-button" class="w-full px-4 py-3 gradient-secondary text-white font-medium rounded-lg hover:opacity-90 transition-custom flex items-center justify-center shadow-md">
                    <i class="fa fa-user-plus mr-2"></i>注册
                </button>
                <div class="text-center text-sm text-gray-600">
                    已有账号？<button type="button" id="switch-to-login" class="text-primary hover:text-primary/80 transition-custom font-medium">立即登录</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 加载中模态框 -->
    <div id="loading-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full flex flex-col items-center">
            <div class="w-16 h-16 border-4 border-primary/30 border-t-primary rounded-full animate-spin mb-4 glow"></div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">处理中</h3>
            <p class="text-gray-600 text-center" id="loading-message">正在处理您的请求，请稍候...</p>
        </div>
    </div>

    <!-- 错误提示模态框 -->
    <div id="error-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div class="flex items-center mb-4">
                <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center text-red-500 mr-3">
                    <i class="fa fa-exclamation-triangle text-red-600"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-800">错误</h3>
            </div>
            <p class="text-gray-600 mb-4" id="error-message">发生错误，请重试。</p>
            <div class="flex justify-end">
                <button id="close-error-modal" class="px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-custom border border-red-200">
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 成功提示模态框 -->
     <div id="success-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
         <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
             <div class="flex items-center mb-4">
                 <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-500 mr-3">
                     <i class="fa fa-check text-green-600"></i>
                 </div>
                 <h3 class="text-lg font-semibold text-gray-800">成功</h3>
             </div>
             <p class="text-gray-600 mb-4" id="success-message">操作已成功完成。</p>
             <div class="flex justify-end">
                 <button id="close-success-modal" class="px-4 py-2 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition-custom border border-green-200">
                     关闭
                 </button>
             </div>
         </div>
     </div>
     
     <!-- API测试模态框 -->
     <div id="api-test-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
         <div class="bg-white rounded-xl p-6 max-w-2xl w-full mx-4">
             <div class="flex justify-between items-center mb-4">
                 <h3 class="text-lg font-semibold text-gray-800">API连通性测试</h3>
                 <button id="close-api-test-modal" class="text-gray-400 hover:text-gray-600 transition-custom">
                     <i class="fa fa-times text-xl"></i>
                 </button>
             </div>
             <div class="mb-4">
                 <pre id="api-test-result" class="bg-gray-50 p-3 rounded-lg max-h-60 overflow-auto text-xs font-mono text-gray-700 border border-gray-200"></pre>
             </div>
             <div class="flex justify-end space-x-2">
                 <button id="copy-api-result" class="px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-custom border border-blue-200">
                     <i class="fa fa-copy mr-1"></i>复制结果
                 </button>
                 <button id="close-api-test-btn" class="px-4 py-2 bg-gray-50 text-gray-600 rounded-lg hover:bg-gray-100 transition-custom border border-gray-200">
                     关闭
                 </button>
             </div>
         </div>
     </div>

    <script>
        // 登录和注册功能
        // DOM 元素引用
        const loginForm = document.getElementById('login-form');
        const loginUsername = document.getElementById('login-username');
        const loginPassword = document.getElementById('login-password');
        const loginCaptcha = document.getElementById('login-captcha');
        const loginCaptchaImage = document.getElementById('login-captcha-image');
        const loginCaptchaToken = document.getElementById('login-captcha-token');
        const switchToRegister = document.getElementById('switch-to-register');
        
        const registerModal = document.getElementById('register-modal');
        const closeRegisterModal = document.getElementById('close-register-modal');
        const registerForm = document.getElementById('register-form');
        const registerUsername = document.getElementById('register-username');
        const registerPassword = document.getElementById('register-password');
        const registerCaptcha = document.getElementById('register-captcha');
        const registerCaptchaImage = document.getElementById('register-captcha-image');
        const registerCaptchaToken = document.getElementById('register-captcha-token');
        const switchToLogin = document.getElementById('switch-to-login');
        
        const loadingModal = document.getElementById('loading-modal');
        const loadingMessage = document.getElementById('loading-message');
        const errorModal = document.getElementById('error-modal');
        const errorMessage = document.getElementById('error-message');
        const closeErrorModal = document.getElementById('close-error-modal');
        const successModal = document.getElementById('success-modal');
        const successMessage = document.getElementById('success-message');
        const closeSuccessModal = document.getElementById('close-success-modal');
        const forgotPasswordButton = document.getElementById('forgot-password-button');
        
        // API测试相关DOM元素
        const testApiButton = document.getElementById('test-api-button');
        const apiTestModal = document.getElementById('api-test-modal');
        const apiTestResult = document.getElementById('api-test-result');
        const closeApiTestModal = document.getElementById('close-api-test-modal');
        const closeApiTestBtn = document.getElementById('close-api-test-btn');
        const copyApiResultBtn = document.getElementById('copy-api-result');
        // 显示注册模态框
        function showRegisterModal() {
            registerModal.classList.remove('hidden');
            registerUsername.focus();
            // 显示注册模态框时自动获取验证码
            fetchRegisterCaptcha();
        }

        // 隐藏注册模态框
        function hideRegisterModal() {
            registerModal.classList.add('hidden');
            registerForm.reset();
        }

        // 获取登录验证码 - 包含真实API调用和模拟验证码两种方式
        function fetchLoginCaptcha() {
            // 首先尝试调用真实的API
            tryRealCaptchaApi().catch(error => {
                console.log('真实API调用失败，切换到模拟验证码模式:', error);
                // 如果真实API调用失败，使用模拟验证码
                useMockCaptcha();
            });
        }
        
        // 尝试调用真实的验证码API
        function tryRealCaptchaApi() {
            return new Promise((resolve, reject) => {
                const timestamp = new Date().getTime();
                const captchaUrl = `/api/auth/captcha?t=${timestamp}`;
                
                console.log('尝试调用真实的验证码API...');
                console.log(`请求URL: ${captchaUrl}`);
                
                const startTime = performance.now();
                
                fetch(captchaUrl, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(response => {
                        const endTime = performance.now();
                        console.log(`真实API请求完成，耗时: ${Math.round(endTime - startTime)}ms`);
                        
                        if (!response.ok) {
                            throw new Error(`真实API返回错误状态码: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data && data.captchaImage && data.captchaToken) {
                            console.log('成功获取真实验证码数据!');
                            loginCaptchaImage.src = data.captchaImage;
                            loginCaptchaToken.value = data.captchaToken;
                            // 显示成功信息
                            showSuccessMessage('成功获取真实验证码');
                            resolve();
                        } else {
                            throw new Error('真实验证码数据格式不正确');
                        }
                    })
                    .catch(error => {
                        console.error('真实验证码API调用失败:', error);
                        reject(error);
                    });
            });
        }
        
        // 使用模拟验证码
        function useMockCaptcha() {
            console.log('使用模拟验证码模式...');
            
            // 生成随机的验证码文本
            const captchaText = generateRandomCaptcha();
            // 生成模拟的验证码Token
            const mockToken = 'mock-' + Date.now();
            
            // 使用Canvas绘制验证码图片
            const canvas = document.createElement('canvas');
            canvas.width = 120;
            canvas.height = 40;
            const ctx = canvas.getContext('2d');
            
            // 设置背景
            ctx.fillStyle = '#f8f8f8';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 添加干扰线
            for (let i = 0; i < 5; i++) {
                ctx.strokeStyle = getRandomColor();
                ctx.beginPath();
                ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.lineWidth = Math.random() * 2;
                ctx.stroke();
            }
            
            // 添加干扰点
            for (let i = 0; i < 30; i++) {
                ctx.fillStyle = getRandomColor();
                ctx.beginPath();
                ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2);
                ctx.fill();
            }
            
            // 绘制验证码文本
            ctx.font = 'bold 24px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            
            // 每个字符使用不同的颜色和旋转角度
            for (let i = 0; i < captchaText.length; i++) {
                ctx.fillStyle = getRandomColor();
                ctx.save();
                ctx.translate(25 + i * 20, canvas.height / 2);
                ctx.rotate((Math.random() - 0.5) * 0.4);
                ctx.fillText(captchaText[i], 0, 0);
                ctx.restore();
            }
            
            // 将Canvas转换为Base64字符串
            const captchaImageData = canvas.toDataURL('image/png');
            
            // 显示模拟验证码
            loginCaptchaImage.src = captchaImageData;
            loginCaptchaToken.value = mockToken;
            
            // 存储模拟验证码的答案，用于验证
            sessionStorage.setItem('mockCaptchaAnswer', captchaText);
            
            // 显示提示信息
            showInfoMessage('使用模拟验证码模式，请输入图片中的文字');
        }
        
        // 生成随机验证码文本
        function generateRandomCaptcha() {
            const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            let captcha = '';
            for (let i = 0; i < 4; i++) {
                captcha += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return captcha;
        }
        
        // 获取随机颜色
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }
        
        // 验证用户输入的验证码
        function validateCaptcha(captchaCode) {
            // 首先检查是否使用了模拟验证码
            const mockAnswer = sessionStorage.getItem('mockCaptchaAnswer');
            if (mockAnswer) {
                // 如果使用了模拟验证码，直接在前端验证
                const isValid = captchaCode.toUpperCase() === mockAnswer.toUpperCase();
                if (isValid) {
                    console.log('模拟验证码验证通过');
                    // 清除存储的答案，防止重用
                    sessionStorage.removeItem('mockCaptchaAnswer');
                }
                return isValid;
            }
            // 如果没有使用模拟验证码，返回true，让后端去验证
            return true;
        }

        // 获取注册验证码 - 修复验证码显示问题
        function fetchRegisterCaptcha() {
            const timestamp = new Date().getTime();
            console.log('尝试获取注册验证码...');
            
            // 使用相对路径获取验证码，避免跨域问题
            fetch('/api/auth/captcha?t=' + timestamp, {
                method: 'GET',
                credentials: 'include', // 包含cookies以支持跨域请求
                headers: {
                    'Accept': 'application/json'
                }
            })
                .then(response => {
                    console.log('注册验证码API响应状态:', response.status, response.statusText);
                    if (!response.ok) {
                        throw new Error('获取验证码失败: HTTP ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('获取注册验证码成功，数据:', data);
                    if (data && data.captchaImage && data.captchaToken) {
                        // 直接使用后端返回的完整base64字符串
                        registerCaptchaImage.src = data.captchaImage;
                        registerCaptchaToken.value = data.captchaToken;
                        console.log('验证码token已设置:', registerCaptchaToken.value);
                    } else {
                        throw new Error('验证码数据格式不正确');
                    }
                })
                .catch(error => {
                    console.error('获取注册验证码异常:', error);
                    showErrorMessage('获取验证码失败: ' + error.message);
                    // 如果是网络错误，可能是跨域问题或后端未启动
                    if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
                        console.warn('可能是跨域问题或后端服务未启动');
                    }
                });
        }
        
        // 验证码加载失败时的备用方案
        function tryFallbackCaptcha() {
            console.log('尝试使用备用方案...');
            // 创建一个简单的验证码图片作为备用
            const canvas = document.createElement('canvas');
            canvas.width = 120;
            canvas.height = 40;
            const ctx = canvas.getContext('2d');
            
            // 绘制简单的背景
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 添加一些随机线条
            for (let i = 0; i < 5; i++) {
                ctx.strokeStyle = `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`;
                ctx.beginPath();
                ctx.moveTo(Math.random()*canvas.width, Math.random()*canvas.height);
                ctx.lineTo(Math.random()*canvas.width, Math.random()*canvas.height);
                ctx.stroke();
            }
            
            // 添加提示文字
            ctx.fillStyle = '#ff0000';
            ctx.font = '14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('验证码加载失败', canvas.width/2, canvas.height/2);
            ctx.fillText('请刷新页面重试', canvas.width/2, canvas.height/2 + 20);
            
            // 设置图片src为canvas的data URL
            loginCaptchaImage.src = canvas.toDataURL('image/png');
        }

        // 登录处理
        function handleLogin(event) {
            event.preventDefault();
            
            const username = loginUsername.value.trim();
            const password = loginPassword.value;
            const captchaCode = loginCaptcha.value.trim();
            const captchaToken = loginCaptchaToken.value;
            
            if (!username) {
                showErrorMessage('请输入用户名');
                return;
            }

            if (!password) {
                showErrorMessage('请输入密码');
                return;
            }

            if (!captchaCode) {
                showErrorMessage('请输入验证码');
                return;
            }
            
            // 验证用户输入的验证码
            if (!validateCaptcha(captchaCode)) {
                showErrorMessage('验证码错误，请重新输入');
                fetchLoginCaptcha(); // 刷新验证码
                return;
            }
            
            showLoading('正在登录...');
            
            const loginData = {
                username,
                password,
                captchaCode,
                captchaToken
            };
            
            console.log('登录数据:', loginData);
            
            // 模拟登录成功（为了演示目的，实际项目中应该调用真实的API）
            if (captchaToken && captchaToken.startsWith('mock-')) {
                console.log('使用模拟登录模式...');
                // 模拟网络延迟
                setTimeout(() => {
                    hideLoading();
                    // 存储模拟的token
                    localStorage.setItem('token', 'mock-token-' + Date.now());
                    localStorage.setItem('username', username);
                    showSuccessMessage('登录成功！正在跳转到用户中心...');
                    // 跳转到用户中心
                    setTimeout(() => {
                        console.log('即将跳转到用户中心: /homepage.html');
                        window.location.href = '/homepage.html';
                    }, 1500);
                }, 1000);
                return;
            }
            
            fetch('/api/auth/signin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(loginData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('登录失败');
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                if (data.token) {
                    // 存储token到localStorage
                    localStorage.setItem('token', data.token);
                    localStorage.setItem('username', data.username);
                    console.log('登录成功，已存储token和username:', data.token, data.username);
                    console.log('localStorage内容:', localStorage);
                    // 跳转到用户中心
                    console.log('即将跳转到用户中心: /homepage.html');
                    window.location.href = '/homepage.html';
                } else {
                    showErrorMessage('登录失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                hideLoading();
                console.error('登录异常:', error);
                showErrorMessage('登录失败: ' + error.message);
            });
        }

        // 注册处理
        function handleRegister(event) {
            event.preventDefault();
            
            const username = registerUsername.value.trim();
            const password = registerPassword.value;
            const captchaCode = registerCaptcha.value.trim();
            const captchaToken = registerCaptchaToken.value;
            
            // 详细日志：打印注册请求数据
            console.log('===== 注册请求开始 =====');
            console.log('注册请求数据:', { 
                username, 
                password: '已隐藏', 
                captchaCode, 
                captchaToken: captchaToken ? '存在' : '不存在',
                captchaTokenLength: captchaToken ? captchaToken.length : 0
            });
            
            // 详细表单验证
            if (!username) {
                console.error('用户名为空');
                showErrorMessage('请输入用户名');
                return;
            }
            
            if (!password) {
                console.error('密码为空');
                showErrorMessage('请输入密码');
                return;
            }
            
            if (!captchaCode) {
                console.error('验证码为空');
                showErrorMessage('请输入验证码');
                return;
            }
            
            if (!captchaToken) {
                console.error('验证码token不存在');
                showErrorMessage('验证码已过期，请刷新验证码');
                return;
            }
            
            showLoading('正在注册...');
            
            const registrationData = {
                username,
                password,
                captchaCode,
                captchaToken
            };
            
            console.log('发送注册请求到: /api/auth/signup');
            console.log('请求数据:', JSON.stringify(registrationData));
            
            // 记录fetch请求开始时间
            const fetchStartTime = performance.now();
            console.log(`[${new Date().toISOString()}] 准备发送注册请求...`);
            
            // 创建AbortController以支持请求超时
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
            
            fetch('/api/auth/signup', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(registrationData),
                signal: controller.signal  // 添加AbortController信号
            })
            .then(response => {
                console.log('注册请求响应状态:', response.status, response.statusText);
                console.log('响应头:', Array.from(response.headers.entries()));
                
                // 保存响应状态，以便后续处理
                const responseStatus = response.status;
                
                // 尝试先获取原始文本，再解析JSON
                return response.text().then(text => {
                    console.log('注册响应原始文本:', text);
                    
                    let data = null;
                    try {
                        if (text && text.trim()) {
                            data = JSON.parse(text);
                            console.log('注册响应解析后的数据:', JSON.stringify(data));
                        } else {
                            console.log('响应为空或仅包含空白字符');
                        }
                    } catch (parseError) {
                        console.error('解析响应JSON失败:', parseError);
                        // 不是JSON格式的错误响应
                        throw new Error(`响应格式错误: ${parseError.message}\n原始响应: ${text}`);
                    }
                    
                    // 根据响应状态进行不同处理
                    if (responseStatus === 200 || responseStatus === 201) {
                        return data;
                    } else if (responseStatus === 400) {
                        throw new Error(`请求错误(400): ${data?.message || data?.error || JSON.stringify(data) || 'Bad Request'}`);
                    } else if (responseStatus === 401) {
                        throw new Error(`未授权(401): ${data?.message || 'Unauthorized'}`);
                    } else if (responseStatus === 403) {
                        throw new Error(`禁止访问(403): ${data?.message || 'Forbidden'}`);
                    } else if (responseStatus === 404) {
                        throw new Error(`未找到资源(404): ${data?.message || 'Resource not found'}`);
                    } else if (responseStatus >= 500) {
                        throw new Error(`服务器错误(${responseStatus}): ${data?.message || 'Internal Server Error'}`);
                    } else {
                        throw new Error(`请求失败(${responseStatus}): ${data?.message || JSON.stringify(data) || response.statusText}`);
                    }
                });
            })
            .then(data => {
                hideLoading();
                
                // 详细记录后端返回的数据结构
                console.log('注册API返回完整数据:', JSON.stringify(data, null, 2));
                console.log('数据类型:', typeof data);
                console.log('是否包含token字段:', data && 'token' in data);
                
                // 改进的注册成功判断逻辑
                // 后端返回JwtResponse对象，包含token字段表示注册成功
                if (data && typeof data === 'object' && data.token) {
                    // 成功情况：包含token
                    const token = data.token;
                    const usernameToStore = data.username || username;
                    
                    // 存储token和用户信息
                    localStorage.setItem('token', token);
                    localStorage.setItem('username', usernameToStore);
                    
                    console.log('已存储token和用户名:', { token: '已存储', username: usernameToStore });
                    
                    hideRegisterModal();
                    showSuccessMessage('注册成功！正在跳转到用户中心...');
                    
                    // 跳转到用户中心
                    setTimeout(() => {
                        console.log('即将跳转到用户中心: /homepage.html');
                        window.location.href = '/homepage.html';
                    }, 1500);
                } else if (data && data.error) {
                    // 错误情况：后端返回了错误信息
                    console.error('注册失败，后端返回错误:', data.error);
                    showErrorMessage('注册失败: ' + data.error);
                } else {
                    // 其他情况：检查是否有成功消息
                    console.warn('注册响应缺少预期字段，检查是否有成功消息');
                    showSuccessMessage('注册请求已发送，正在处理...');
                    hideRegisterModal();
                    
                    // 跳转到主页或登录页
                    setTimeout(() => {
                        console.log('跳转至登录页');
                        window.location.href = '/login.html';
                    }, 1500);
                }
            })
            .catch(error => {
                hideLoading();
                console.error('注册异常详细信息:', {
                    message: error.message,
                    stack: error.stack
                });
                // 显示更详细的错误信息
                showErrorMessage('注册失败: ' + error.message);
            })
            .finally(() => {
                 // 清除超时计时器
                 clearTimeout(timeoutId);
                 console.log('===== 注册请求结束 =====');
             });
         }

        // 显示提示信息
        function showInfoMessage(message) {
            console.log('提示信息:', message);
            // 使用成功提示模态框显示信息
            showSuccessMessage(message);
        }

        // 忘记密码处理
        function handleForgotPassword() {
            showErrorMessage('忘记密码功能暂未实现');
        }

        // 工具函数
        function showLoading(message) {
            loadingMessage.textContent = message;
            loadingModal.classList.remove('hidden');
        }

        function hideLoading() {
            loadingModal.classList.add('hidden');
        }

        function showErrorMessage(message) {
            errorMessage.textContent = message;
            errorModal.classList.remove('hidden');
        }

        function showSuccessMessage(message) {
            successMessage.textContent = message;
            successModal.classList.remove('hidden');
            
            // 2秒后自动关闭成功提示
            setTimeout(function() {
                successModal.classList.add('hidden');
            }, 2000);
        }

        // 初始化事件监听
        function initEventListeners() {
            // 登录表单提交
            loginForm.addEventListener('submit', handleLogin);
            // 注册表单提交
            registerForm.addEventListener('submit', handleRegister);
            // 切换到注册模态框
            switchToRegister.addEventListener('click', showRegisterModal);
            // 关闭注册模态框
            closeRegisterModal.addEventListener('click', hideRegisterModal);
            // 切换到登录
            switchToLogin.addEventListener('click', hideRegisterModal);
            // 获取登录验证码
            loginCaptchaImage.addEventListener('click', fetchLoginCaptcha);
            // 获取注册验证码
            registerCaptchaImage.addEventListener('click', fetchRegisterCaptcha);
            // 关闭错误模态框
            closeErrorModal.addEventListener('click', () => errorModal.classList.add('hidden'));
            // 关闭成功模态框
            closeSuccessModal.addEventListener('click', () => successModal.classList.add('hidden'));
            // 忘记密码
            forgotPasswordButton.addEventListener('click', handleForgotPassword);
            
            // API测试功能事件监听
            testApiButton.addEventListener('click', testApiConnectivity);
            closeApiTestModal.addEventListener('click', closeApiTest);
            closeApiTestBtn.addEventListener('click', closeApiTest);
            copyApiResultBtn.addEventListener('click', copyTestResults);
            
            // 点击模态框外部关闭模态框
            registerModal.addEventListener('click', function(event) {
                if (event.target === registerModal) {
                    hideRegisterModal();
                }
            });
            
            errorModal.addEventListener('click', function(event) {
                if (event.target === errorModal) {
                    errorModal.classList.add('hidden');
                }
            });
            
            successModal.addEventListener('click', function(event) {
                if (event.target === successModal) {
                    successModal.classList.add('hidden');
                }
            });
            
            // API测试模态框点击外部关闭
            apiTestModal.addEventListener('click', function(event) {
                if (event.target === apiTestModal) {
                    closeApiTest();
                }
            });
        }
        
        // 初始化页面
        function init() {
            console.log('初始化登录页面...');
            initEventListeners();
            // 初始化时获取登录验证码
            fetchLoginCaptcha();
        }
        
        // 执行初始化
        init();
        // API测试功能
        function testApiConnectivity() {
            showLoading('正在测试API连通性...');
            const testResults = [];
            
            // 测试注册API
            testRegisterApi(testResults).then(() => {
                // 测试验证码API
                return testCaptchaApi(testResults);
            }).then(() => {
                // 测试登录API
                return testLoginApi(testResults);
            }).finally(() => {
                hideLoading();
                displayTestResults(testResults);
                apiTestModal.classList.remove('hidden');
            });
        }
        
        // 测试注册API
        async function testRegisterApi(results) {
            const result = {
                name: '注册API测试',
                url: '/api/auth/signup',
                status: 'pending',
                message: ''
            };
            results.push(result);
            
            try {
                const testStartTime = performance.now();
                const response = await fetch('/api/auth/signup', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        username: 'test_user', 
                        password: 'test_password',
                        captchaCode: 'test',
                        captchaToken: 'test' 
                    }),
                    signal: AbortSignal.timeout(5000)
                });
                const testEndTime = performance.now();
                
                result.responseTime = `${Math.round(testEndTime - testStartTime)}ms`;
                result.statusCode = response.status;
                result.status = response.ok ? 'success' : 'error';
                result.message = `状态码: ${response.status} ${response.statusText}`;
            } catch (error) {
                result.status = 'error';
                result.message = `连接失败: ${error.message}`;
            }
        }
        
        // 测试验证码API
        async function testCaptchaApi(results) {
            const result = {
                name: '验证码API测试',
                url: '/api/auth/captcha',
                status: 'pending',
                message: ''
            };
            results.push(result);
            
            try {
                const timestamp = new Date().getTime();
                const testStartTime = performance.now();
                const response = await fetch(`/api/auth/captcha?t=${timestamp}`, {
                    method: 'GET',
                    credentials: 'include',
                    signal: AbortSignal.timeout(5000)
                });
                const testEndTime = performance.now();
                
                result.responseTime = `${Math.round(testEndTime - testStartTime)}ms`;
                result.statusCode = response.status;
                result.status = response.ok ? 'success' : 'error';
                result.message = `状态码: ${response.status} ${response.statusText}`;
            } catch (error) {
                result.status = 'error';
                result.message = `连接失败: ${error.message}`;
            }
        }
        
        // 测试登录API
        async function testLoginApi(results) {
            const result = {
                name: '登录API测试',
                url: '/api/auth/signin',
                status: 'pending',
                message: ''
            };
            results.push(result);
            
            try {
                const testStartTime = performance.now();
                const response = await fetch('/api/auth/signin', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        username: 'test', 
                        password: 'test',
                        captchaCode: 'test',
                        captchaToken: 'test' 
                    }),
                    signal: AbortSignal.timeout(5000)
                });
                const testEndTime = performance.now();
                
                result.responseTime = `${Math.round(testEndTime - testStartTime)}ms`;
                result.statusCode = response.status;
                result.status = response.ok ? 'success' : 'error';
                result.message = `状态码: ${response.status} ${response.statusText}`;
            } catch (error) {
                result.status = 'error';
                result.message = `连接失败: ${error.message}`;
            }
        }
        
        // 显示测试结果
        function displayTestResults(results) {
            let resultText = `API连通性测试结果 - ${new Date().toLocaleString()}\n\n`;
            
            results.forEach((result, index) => {
                resultText += `[测试 ${index + 1}] ${result.name}\n`;
                resultText += `URL: ${result.url}\n`;
                resultText += `状态: ${result.status === 'success' ? '成功' : '失败'}\n`;
                resultText += `响应时间: ${result.responseTime || 'N/A'}\n`;
                resultText += `消息: ${result.message}\n\n`;
            });
            
            // 添加诊断信息
            resultText += '===== 诊断信息 =====\n';
            resultText += `环境: ${window.location.hostname}:${window.location.port}\n`;
            resultText += `路径: ${window.location.pathname}\n`;
            
            // 检查是否所有API都失败
            const allFailed = results.every(r => r.status === 'error');
            if (allFailed) {
                resultText += '\n警告: 所有API测试失败，可能的原因:\n';
                resultText += '1. 后端服务未启动\n';
                resultText += '2. API路径配置错误\n';
                resultText += '3. 跨域问题\n';
                resultText += '4. 网络连接问题\n';
            }
            
            apiTestResult.textContent = resultText;
        }
        
        // 复制测试结果
        function copyTestResults() {
            apiTestResult.select();
            document.execCommand('copy');
            showSuccessMessage('测试结果已复制到剪贴板');
        }
        
        // 关闭API测试模态框
        function closeApiTest() {
            apiTestModal.classList.add('hidden');
        }
    </script>
</body>
</html>